﻿using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Sms.V20210111;
using TencentCloud.Sms.V20210111.Models;

namespace Sgr.Sms.TencentCloud
{
    /// <summary>
    /// 腾讯云短信服务提供者
    /// </summary>
    public class TencentCloudSmsProvider : ISmsProvider, IDisposable
    {
        private readonly TencentCloudSmsOptions _options;
        private readonly ILogger<TencentCloudSmsProvider> _logger;
        private readonly Lazy<SmsClient> _client;
        private bool _disposed;

        public string Name => "TENCENT_CLOUD";

        public TencentCloudSmsProvider(
            IOptions<TencentCloudSmsOptions> options,
            ILogger<TencentCloudSmsProvider> logger)
        {
            _options = options?.Value ?? throw new ArgumentNullException(nameof(options));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));

            // 延迟初始化 SmsClient
            _client = new Lazy<SmsClient>(() => CreateSmsClient());
        }

        private SmsClient CreateSmsClient()
        {
            var cred = new Credential
            {
                SecretId = _options.SecretId,
                SecretKey = _options.SecretKey
            };

            var clientProfile = new ClientProfile();
            var httpProfile = new HttpProfile
            {
                Endpoint = "sms.tencentcloudapi.com"
            };
            clientProfile.HttpProfile = httpProfile;

            return new SmsClient(cred, _options.Region, clientProfile);
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        public async Task<SmsResult> SendAsync(
            string phoneNumber,
            string message,
            CancellationToken cancellationToken = default)
        {
            ThrowIfDisposed();

            try
            {
                // 检查参数
                if (string.IsNullOrWhiteSpace(phoneNumber))
                    return SmsResult.Failure("手机号不能为空");

                if (string.IsNullOrWhiteSpace(message))
                    return SmsResult.Failure("短信内容不能为空");

                // 验证手机号格式
                if (!phoneNumber.StartsWith("+86"))
                    phoneNumber = "+86" + phoneNumber;

                _logger.LogInformation(
                    "准备发送腾讯云短信: PhoneNumber={PhoneNumber}, Content={Content}",
                    phoneNumber,
                    message);

                // 创建发送短信请求
                var req = new SendSmsRequest
                {
                    PhoneNumberSet = new string[] { phoneNumber },
                    SmsSdkAppId = _options.SdkAppId,
                    SignName = _options.SignName,
                    TemplateId = _options.TemplateId, // 注意：腾讯云需要使用模板ID，而不是直接发送内容
                    TemplateParamSet = new string[] { message }
                };

                // 发送短信
                var resp = await _client.Value.SendSms(req);

                // 检查发送结果
                if (resp.SendStatusSet[0].Code == "Ok")
                {
                    _logger.LogInformation(
                        "腾讯云短信发送成功: PhoneNumber={PhoneNumber}, MessageId={MessageId}",
                        phoneNumber,
                        resp.SendStatusSet[0].SerialNo);

                    return SmsResult.Success();
                }

                var error = $"错误码：{resp.SendStatusSet[0].Code}，错误信息：{resp.SendStatusSet[0].Message}";
                _logger.LogWarning(
                    "腾讯云短信发送失败: PhoneNumber={PhoneNumber}, Error={Error}",
                    phoneNumber,
                    error);

                return SmsResult.Failure(error);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex,
                    "腾讯云短信发送异常: PhoneNumber={PhoneNumber}",
                    phoneNumber);

                return SmsResult.Failure($"短信发送异常: {ex.Message}");
            }
        }

        protected virtual void ThrowIfDisposed()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(nameof(TencentCloudSmsProvider));
            }
        }

        public void Dispose()
        {
            if (!_disposed)
            {
                if (_client.IsValueCreated)
                {
                    //_client.Value.HttpClient?.Dispose();
                }
                _disposed = true;
            }
            GC.SuppressFinalize(this);
        }
    }
}